package jackjson.demo01;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import jackjson.demo01.pojo.Children;
import jackjson.demo01.pojo.Person;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author cyt
 * @create 2020-07-29 20:19
 */
@Slf4j
public class ParseJson {
    /**
     * 转化为 json
     *
     * @param args
     */
    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        Person person = new Person( );
        person.setName("cyt");
        Children children = new Children();
        children.setName("ff");
        person.setChildren(children);

        String json = mapper.writeValueAsString(person);
        log.info("person => "+ json);


        ArrayList<Person> personArrayList = new ArrayList<>();
        personArrayList.add(new Person("asd",children));
        personArrayList.add(new Person("fgh",children));
        personArrayList.add(new Person("jkl",children));
        String listJson = mapper.writeValueAsString(personArrayList);
        log.info("list => " + listJson);


        HashMap<String, Object> personMap = new HashMap<>(3);
        personMap.put("v1", new Person("asd",children));
        personMap.put("v2",personArrayList);
        String mapjson = mapper.writeValueAsString(personMap);
        log.info("map = > "+ mapjson);

        Person readValue = mapper.readValue(json, Person.class);
        log.info("person =>"+ readValue.toString());

        List<Person> list = mapper.readValue(listJson, new TypeReference<ArrayList<Person>>() {});

        for (Person person1 : list) {
            log.info(person1.toString());
        }

        Map map = mapper.readValue(mapjson, new TypeReference<Map>() {
        });

        System.out.println(map.toString());
    }
}



